"""
API路由 - 学生、课程、成绩等资源管理
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.blueprints.api import api_bp
from app.models.user import User, StudentProfile, TeacherProfile
from app.models.course import Course, CourseTag
from app.models.student_course import StudentCourse
from app.extensions import db

# 导入管理功能路由
from app.blueprints.api import import_routes
from app.blueprints.api import user_management
from app.blueprints.api import course_management
from app.blueprints.api import system_settings
from app.blueprints.api import teacher_management
from app.blueprints.api import student_enrollment


@api_bp.route('/students', methods=['GET'])
@jwt_required()
def get_students():
    """获取学生列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        
        query = User.query.filter_by(role='student')
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        students = []
        for user in pagination.items:
            student_data = user.to_dict()
            if user.student_profile:
                student_data['profile'] = user.student_profile.to_dict()
            students.append(student_data)
        
        return jsonify({
            'success': True,
            'data': students,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/students/<int:student_id>', methods=['GET'])
@jwt_required()
def get_student(student_id):
    """获取学生详细信息"""
    try:
        user = User.query.get(student_id)
        
        if not user or user.role != 'student':
            return jsonify({
                'success': False,
                'error': 'Student not found'
            }), 404
        
        student_data = user.to_dict()
        if user.student_profile:
            student_data['profile'] = user.student_profile.to_dict()
        
        # 获取选课记录
        from app.models.student_course import StudentCourse
        student_courses = StudentCourse.query.filter_by(student_id=student_id).all()
        courses = []
        for sc in student_courses:
            course_data = sc.to_dict()
            if sc.course:
                course_data['course'] = sc.course.to_dict()
            courses.append(course_data)
        
        student_data['courses'] = courses
        
        return jsonify({
            'success': True,
            'data': student_data
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/courses', methods=['GET'])
@jwt_required()
def get_courses():
    """获取课程列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        department = request.args.get('department')
        semester = request.args.get('semester')
        
        query = Course.query
        
        if department:
            query = query.filter_by(department=department)
        if semester:
            query = query.filter_by(semester=semester)
        
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        courses = []
        for course in pagination.items:
            course_data = course.to_dict()
            # 添加选课人数
            course_data['enrollment_count'] = StudentCourse.query.filter_by(course_id=course.id).count()
            courses.append(course_data)
        
        return jsonify({
            'success': True,
            'data': courses,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/courses/<int:course_id>', methods=['GET'])
@jwt_required()
def get_course(course_id):
    """获取课程详细信息"""
    try:
        course = Course.query.get(course_id)
        
        if not course:
            return jsonify({
                'success': False,
                'error': 'Course not found'
            }), 404
        
        course_data = course.to_dict()
        
        # 获取教师信息
        if course.instructor:
            course_data['instructor'] = {
                'id': course.instructor.id,
                'username': course.instructor.username,
                'first_name': course.instructor.first_name,
                'last_name': course.instructor.last_name
            }
        
        # 获取选课学生数
        enrollment_count = StudentCourse.query.filter_by(course_id=course_id).count()
        course_data['enrollment_count'] = enrollment_count
        
        return jsonify({
            'success': True,
            'data': course_data
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teachers', methods=['GET'])
@jwt_required()
def get_teachers():
    """获取教师列表"""
    try:
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 20, type=int)
        
        query = User.query.filter_by(role='teacher')
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        teachers = []
        for user in pagination.items:
            teacher_data = user.to_dict()
            if user.teacher_profile:
                teacher_data['profile'] = user.teacher_profile.to_dict()
            teachers.append(teacher_data)
        
        return jsonify({
            'success': True,
            'data': teachers,
            'pagination': {
                'page': page,
                'per_page': per_page,
                'total': pagination.total,
                'pages': pagination.pages
            }
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@api_bp.route('/teachers/<int:teacher_id>/courses', methods=['GET'])
@jwt_required()
def get_teacher_courses(teacher_id):
    """获取教师所授课程"""
    try:
        user = User.query.get(teacher_id)
        
        if not user or user.role != 'teacher':
            return jsonify({
                'success': False,
                'error': 'Teacher not found'
            }), 404
        
        courses = [course.to_dict() for course in user.courses_taught]
        
        return jsonify({
            'success': True,
            'data': courses
        }), 200
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

